<?php
/**
 * MFN构造器
 * @author Kane
 * */
namespace App\Common\Product;

use App\Model\Product\Product;

class MFN
{

    use \App\Common\Cache;

    protected static $year = null;

	/**
	 * 获取年份
	 * @param $mfn string
	 * @return string
	 * */
	public static function year ()
	{
		return self::$year = isset(self::$year) ? self::$year : date('y');
	}


	protected static $month = null;

	/**
	 * 获取月份
	 * @param $mfn string
	 * @return string
	 * */
	public static function month ()
	{
		self::$month = isset(self::$month) ? self::$month : date('n');
		switch (self::$month) {
			case 11:
				return 'a';

			case 12:
				return 'b';

			default:
				return self::$month;
		}
	}



	protected static $length = 'abcdefghijklmn';

	/**
	 * 获取长度
	 * @param $val float 长度值
	 * @return string
	 * */
	public static function length ($val)
	{
		if (!$val) return $val;

		$val = (int)floor($val);
		if ($val<100) {
			return $val<10 ? '0'.$val : $val;
		} else {
			$val = self::{__FUNCTION__}($val/10);
			return substr_replace($val, self::$length[substr($val, 0, 1)], 0, 1);
		}
	}




	/**
	 * 追加设置MFN
	 * @param $mfn string MFN
	 * @param $str string 追加的字符串
	 * */
	public function set (&$mfn, $str='')
	{
		$mfn .= (string)$str;
		return $this;
	}




	/**
	 * 校验判断MFN是否已存在于数据库 并做好最终处理
	 * @param $mfn string
	 * */
	public function check ($mfn)
	{
		$key = $mfn.'-';

		$n = static::cache($key);
		if (isset($n)) {
			self::cache($key, $n+1, 0);
			return $n ? $mfn.'-'.$n : $mfn;
		}

		self::cache($key, Product::where('mfn', 'like', $key.'％')->count(), 0);

		return $this->{__FUNCTION__}($mfn);
	}

}
